package com.vinaprime.primeschedule.presentation;

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.vinaprime.primeschedule.businesslayer.VPConfiguration_BL;
import com.vinaprime.primeschedule.businesslayer.VPLanguage_BL;
import com.vinaprime.primeschedule.entities.VPConfiguration;
import com.vinaprime.primeschedule.entities.VPLanguage;
import com.vinaprime.primeschedule.entities.VPSnoozeSound;

public class SettingActivity extends Activity {

	public final static String SOUND_CHOOSE = "com.vinaprime.primeschedule.presentation.SOUND_CHOOSE";
	public final static int REQUEST_CODE = 1;
	
	private VPConfiguration_BL myConfigBL;
	private VPConfiguration myConfig;
	private ApplicationInformation myAppInfo;
	
	private String myPath;
	
	private SpinnerLanguageAdapter mySpnLangAdapter;
	
	private ArrayList<VPLanguage> myListLang;
	
	private SettingActivity myActivity;
	private Resources myResource;
	
	private Spinner mySpnLang;
	private EditText myEdtxtEmail;
	private EditText myEdtxtSoundName;
	private Switch mySwForceStopFlag;
	private ImageButton myIbtnSound;
	
	private DevicePolicyManager myDevicePolicyManager;
	private ComponentName myComponentName;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting);
		this.myActivity = this;
		
		ActionBar actionBar = getActionBar();
		Drawable d= getResources().getDrawable(R.drawable.background_top_shape_green);  
		actionBar.setBackgroundDrawable(d);
		
		// Initiate DevicePolicyManager.
		myDevicePolicyManager = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
        // Set DeviceAdminDemo Receiver for active the component with different option
		myComponentName = new ComponentName(this, SettingActivity.class);
		
		myAppInfo = new ApplicationInformation(getApplicationContext());
		myPath = myAppInfo.getDBPath();
		
		myConfigBL = new VPConfiguration_BL(getApplicationContext(), myPath);
		myConfig = new VPConfiguration();
		
		myResource = getResources();
		
		myListLang = new ArrayList<VPLanguage>();
		
		setListData();
		
		mySpnLangAdapter = new SpinnerLanguageAdapter(myActivity, R.layout.spinner_language_rows, myListLang, myResource);
		
		myEdtxtSoundName = (EditText)findViewById(R.id.edtxtSoundName);
		myEdtxtEmail = (EditText)findViewById(R.id.edtxtEmail);
		mySwForceStopFlag = (Switch)findViewById(R.id.swForceStopFlag);
		mySpnLang = (Spinner)findViewById(R.id.spnLanguage);
		
		mySpnLang.setAdapter(mySpnLangAdapter);
		mySpnLang.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
            public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
                myConfig.setVpcLanguage(mySpnLangAdapter.getMyLanguage());
            }
 
            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }
		});
		
		loadInfo();
		
		mySwForceStopFlag.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				if(mySwForceStopFlag.isChecked())
					myConfig.setVpcForceStopFlag("Y");
				else
					myConfig.setVpcForceStopFlag("N");
			}
		});
		
		myIbtnSound = (ImageButton)findViewById(R.id.ibtnSound);
		myIbtnSound.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent itnSoundList = new Intent(getApplicationContext(), VpsnoozesoundListActivity.class);
				startActivityForResult(itnSoundList, REQUEST_CODE);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if(resultCode == 1)
		{
			if (data != null)
			{
				myConfig.setVpcSnoozeSound((VPSnoozeSound)data.getSerializableExtra(SOUND_CHOOSE));
				myEdtxtSoundName.setText(myConfig.getVpcSnoozeSound().getVpssFilePath());
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.setting, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(android.view.MenuItem item) {
		Intent mIntent = new Intent(this, MainActivity.class);
		
		switch (item.getItemId()) {
		case R.id.action_cancel:
			startActivity(mIntent);
			break;
		case R.id.action_save:
			VPConfiguration_BL configBL = new VPConfiguration_BL(getApplicationContext(), this.myPath);
			configBL.updateConfiguration(this.myConfig);
			
			startActivity(mIntent);			
			break;
		default:
			break;
		}
		
		return true;
	};
	
	public void loadInfo()
	{
		try
		{
			myConfig = myConfigBL.getConfiguration();
			
			for(int i=0; i<this.myListLang.size(); i++)
			{
				if (myConfig.getVpcLanguage().getVplId() == this.myListLang.get(i).getVplId())
				{
					this.mySpnLang.setSelection(i);
					break;
				}
			}
			
			myEdtxtSoundName.setText(myConfig.getVpcSnoozeSound().getVpssFilePath());
			
			myEdtxtEmail.setText(myConfig.getVpcEmail());
			
			if(myConfig.getVpcForceStopFlag().equals("Y"))
			{
				mySwForceStopFlag.setChecked(true);
			}
			else
			{
				mySwForceStopFlag.setChecked(false);
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}

	public void setListData()
    {
        try
        {
        	VPLanguage_BL langBL = new VPLanguage_BL(getApplicationContext(), myPath);
            myListLang = langBL.getAllLanguageToArray();
        }
        catch (Exception ex)
		{
			ex.printStackTrace();
		}
    }
	
	private class SpinnerLanguageAdapter extends ArrayAdapter{

		private Activity myActivity;
	    private ArrayList myData;
	    public Resources myResource;
	    private VPLanguage myLanguage;
	    LayoutInflater myInflater;
	    
	    public SpinnerLanguageAdapter(SettingActivity activitySpinner, int textViewResourceId, ArrayList objects, Resources resLocal)
	    {
	    	super(activitySpinner, textViewResourceId, objects);
	    	
	    	/********** Take passed values **********/
	        this.myActivity = activitySpinner;
	        this.myData     = objects;
	        this.myResource      = resLocal;
	        this.myLanguage = new VPLanguage();
	    
	        /***********  Layout inflator to call external xml layout () **********************/
	        this.myInflater = (LayoutInflater)this.myActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    }
	    
	    @Override
	    public View getDropDownView(int position, View convertView,ViewGroup parent) {
	        return getCustomView(position, convertView, parent);
	    }
	    
	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	        return getCustomView(position, convertView, parent);
	    }
	 
	    // This funtion called for each row ( Called data.size() times )
	    public View getCustomView(int position, View convertView, ViewGroup parent) {
	    	/********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
	        View row = this.myInflater.inflate(R.layout.spinner_language_rows, parent, false);
	         
	        /***** Get each Model object from Arraylist ********/
	        this.myLanguage = new VPLanguage();
	        this.myLanguage = (VPLanguage) this.myData.get(position);
	        
	        TextView txtvLanguageCode = (TextView)row.findViewById(R.id.txtvLanguageCode);
	        
	    	txtvLanguageCode.setText(this.myLanguage.getVplName());   
	 
	        return row;
	      }

		public VPLanguage getMyLanguage() {
			return myLanguage;
		}    
	    
	}
}
